import imaplib
import time
import PublicDef


def Email_Reamil(request):
    if request.method == 'POST':
        uid = request.POST.get('uid')
        name = request.POST.get('name')
        domain = str(request.POST.get("domain"))
        if len(name) < 1 and len(domain) < 1:
            return PublicDef.ToJsonRep({"msg": "还未申请临时邮箱哟!", "code": "100", "data": []})
        timestamp = str(request.POST.get("timestamp"))
        if (int(time.time() * 1000) - int(timestamp)) > 10000 or (int(timestamp) - int(time.time() * 1000)) > 10000:
            return PublicDef.ToJsonRep({"msg": "会话超时，请检查系统时间是否与北京时间一致！", "code": "100", "data": []})
        Sign_1 = str(request.POST.get("sign"))
        Sign_2 = PublicDef.Sign(name, timestamp)
        if Sign_1 != Sign_2:
            return PublicDef.ToJsonRep({"msg": "无效会话！"})
        if name == "mimo" or name == "chenpur":
            return PublicDef.ToJsonRep({"msg": "您没有权限删除该账号的相关邮件！", "code": "100"})
        ret = Remail(uid, name, domain)
        return PublicDef.ToJsonRep(ret)
    else:
        return PublicDef.ToJsonRep({"msg": "Only POST", "code": "100"})


def Remail(uid, name, domain):
    try:
        box = imaplib.IMAP4_SSL(domain[1:len(domain)])
        box.login(name + domain, "test")
        box.select('Inbox')
        box.store(uid, '+FLAGS', '\\Deleted')
        box.expunge()
        box.close()
        box.logout()
        return {
            "code": "0",
            "msg": "Success"
        }
    except Exception as ex:
        return {
            "code": "100",
            "msg": str(ex)
        }

